<template>
  <!-- 实名认证 -->
  <view class="root">
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @generateFilePath="onGenerateFilePath"
      @parsedSuccess="onParsedSuccess"></yy-photo-mask>
    <view class="realNameAuthentication" v-if="!visibleCamera">
      <view class="wrapper">
        <view class="wrapper-item content">
          <uni-forms ref="form" :model="form" validateTrigger="blur" :border="true" err-show-type="toast"
            label-width="130px">
            <uni-forms-item label="国籍" name="nationality" required>
              <view class="form-content-item" @click="hadleShowPicker('nationality', 'nationality')">
                <uni-easyinput type="text" :disabled="true" v-model="form.nationality_text" disabled
                  disableColor="#ffffff" :inputBorder="false" placeholder="请选择" :clearable="true" />
                <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
              </view>
            </uni-forms-item>
            <uni-forms-item label="证件类型" name="idType" required>
              <view class="form-content-item" @click="hadleShowPicker('certificate_type', 'idType')">
                <uni-easyinput type="text" v-model="form.idType_text" disabled disableColor="#ffffff"
                  :inputBorder="false" placeholder="请选择" :clearable="true" />
                <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
              </view>
            </uni-forms-item>
            <uni-forms-item label="证件照片" name="idCardImage" required>
              <view class="form-content-item" @click="handleToUploadIdcard">
                <view :class="form.idCardImage ? 'long-select-value look-text' : 'long-select-value-empty'">
                  {{form.idCardImage ? '去更换' : '请上传'}}
                </view>
                <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
              </view>
            </uni-forms-item>
            <uni-forms-item label="证件号码" name="idcard" required>
              <view class="form-content-item">
                <uni-easyinput :type="form.idType == 10 ? 'idcard' : 'text'" :maxlength="18" v-model="form.idcard"
                  :inputBorder="false" placeholder="请填写" :clearable="true" @blur="handleIdCardChange" />
                <view v-if="form.idType == 10">
                  <u-icon slot="right" size="21" name="scan" color="#2488F5"
                    @click="handleCamera('houseInfo')"></u-icon>
                </view>
              </view>
            </uni-forms-item>
            <uni-forms-item label="姓名" name="userName" required>
              <view class="form-content-item" :class="form.userName ? '' : 'input-item'">
                <uni-easyinput type="text" v-model="form.userName" :inputBorder="false" placeholder="请填写"
                  :clearable="true" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="民族" name="nation" required>
              <view class="form-content-item" @click="hadleShowPicker('nation', 'nation')">
                <uni-easyinput type="text" :disabled="true" v-model="form.nation_text" disabled disableColor="#ffffff"
                  :inputBorder="false" placeholder="请选择" :clearable="true" />
                <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
              </view>
            </uni-forms-item>
            <uni-forms-item label="手机号" name="mobile" required>
              <view class="form-content-item" :class="form.mobile ? '' : 'input-item'">
                <uni-easyinput type="text" v-model="form.mobile" :inputBorder="false" placeholder="请填写"
                  :clearable="true" />
              </view>
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="tips">
          注意：请确保实名认证的是您本人的信息，以免信息混淆。实名认证一旦完成，修改较为复杂，请谨慎操作。
        </view>
      </view>
      <view class="btns thispageBtn">
        <button class="cancel-btn lt" type="primary" @click="navBack()">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </view>
      <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
        @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
        :defaultIndex="defaultIndex"></u-picker>

      <!-- <yy-city-picker :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false"></yy-city-picker> -->
      <yy-city-picker-all v-if="cityPickerVisible" :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false" :default-value="defaultCityCode"></yy-city-picker-all>
    </view>
  </view>
</template>

<script>
  import pickerMixin from "../../utils/picker-mixin";
  import {
    AuthenticationDetail,
    authentication
  } from "@/api/home.js";

  import {
    Toast,
    navBack,
    uniTrim,
    checkIDCard,
    useNetWork,
    isLoading,
    getHeader,
    uploadFile,
    selectNation,
    setDefaultProvinceCode,
    navTo,
    previewImage,
    getOptionsParams,
  } from "@/utils/util.js";


  import {
    pick,
    debounce
  } from '@/utils/lodash.js'
  import {
    editAuthentication
  } from "../../api/api";

  export default {
    name: "realNameAuthentication",
    mixins: [pickerMixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {
          nation: '',
          // domicileAddress: '',
          // residenceCode: ''
          nationality: 'CHN',
          nationality_text: '中国',
          idType: '10',
          idType_text: '身份证',
          idCardImage: '',
          idCardImageBack: ''
        },
        errorType: ["none"],
        user: uni.getStorageSync("user"),
        fileList: [],
        canvasWidth: 0,
        canvasHeight: 0,

        // 拍摄组件
        cameraContext: {},
        windowHeight: "",
        cameraHeight: "",
        visibleCamera: false,
        layerHeight: 0,
        layerTop: 0,
        layerBottomHeight: 0,
        systemInfo: null,
        cityPickerVisible: false,
        cityPickerWithKey: '',
        oldRealNameAuthentication: {},
        areaList: [],
        defaultCityCode: '',
        routerParams: {},
      };
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)
      uni.$on('saveIdPhoto', (data) => {
        // 赋值最新的照片信息
        this.form.idCardImage = data.idCardImage.map(item => item.halfPath).join('')
        this.form.idCardImageBack = data.idCardImageBack.map(item => item.halfPath).join('')
      })
      this.options = options;
      this.getDetail()

      // 判断是否是否是修改
      if (this.routerParams.action === 'edit') {
        this.form = {
          ...pick(this.routerParams, ['nationality', 'idType', 'idCardImage', 'idCardImageBack', 'idcard',
            'userName',
            'nation',
            'mobile'
          ]),
          idType_text: this.routerParams.idTypeName,
          nationality_text: this.routerParams.nationalityName,
          nation_text: this.routerParams.nationName
        }
      }
    },
    onUnload() {
      uni.$off('saveIdPhoto')
    },
    onShow() {
      const systemInfo = uni.getSystemInfoSync();
      this.systemInfo = systemInfo;
    },
    methods: {
      handleIdCardChange() {
        let params = {
          idCard: this.form.idcard,
        }
        if (this.form.idType == 10) {
          setDefaultProvinceCode.call(this, params, ({
            code,
            address
          }) => {
            this.defaultCityCode = code
            // this.$set(this.form, 'residenceCode_text', address)
            // this.$set(this.form, 'residenceCode', code)
          })
        }
      },
      navBack,
      phoneHandle() {
        if (this.form.mobile && !this.$u.test.mobile(this.form.mobile)) {
          Toast("请输入正确的手机号");
          return;
        }
      },
      onGenerateFilePath(fileurl) {
        this.uploadImage(fileurl, 44)
      },
      uploadImage(fileurl, type) {
        useNetWork(); // 判断是否有网络
        isLoading();
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            if (type == 44) {
              this.fileList = [];
              this.fileList.push({
                url: fullPath,
              });
              uni.hideLoading();
            }
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic() {
        this.fileList = [];
        this.form.idCardImage = "";
      },
      submitHandle() {
        let {
          idCardImage,
          userName,
          idcard,
          mobile,
          nation,
          nationality,
          idType,
          // domicileAddress,
          // residenceCode
        } = this.form;
        if (!nationality) {
          Toast("请选择国籍！");
          return;
        }
        if (!idType) {
          Toast("请选择证件类型！");
          return;
        }
        if (!idCardImage) {
          Toast("请上传证件照片！");
          return;
        }
        if (!idCardImage) {
          Toast("请上传证件照片！");
          return;
        }

        if (!idcard || !uniTrim(idcard)) {
          Toast("请输入证件号码！");
          return;
        }

        let idCardFlag = checkIDCard(idcard);
        if (!idCardFlag && this.form.idType == 10) {
          Toast("请输入正确的证件号码！");
          return;
        }

        if (!userName || !uniTrim(userName)) {
          Toast("请输入姓名！");
          return;
        }

        let legalPersonRegexp =
          /^[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*$/;
        if (!legalPersonRegexp.test(userName) && this.form.idType == 10) {
          Toast("姓名只能输入汉字！");
          return;
        }

        if (!nation) {
          Toast('请选择民族！')
          return
        }

        if (!mobile) {
          Toast("请输入手机号码！");
          return;
        }

        if (mobile && !this.$u.test.mobile(mobile)) {
          Toast("请输入正确的手机号！");
          return;
        }

        let data = {
          ...this.form
        };
        isLoading(true)
        if (this.routerParams.action === 'edit') {
          editAuthentication(data)
            .then((res) => {
              if (res.code == 200) {
                Toast("保存成功！");
                // 更新用户信息
                // this.user.realNameAuthentication = 1;
                this.user.userName = userName
                uni.setStorageSync("user", this.user);
                setTimeout(() => {
                  navBack();
                }, 1000);
                return;
              }
              Toast(res.message);
            })
            .finally(() => {
              isLoading(false)
            })
        } else {
          authentication(data).then((res) => {
              if (res.code == 200) {
                Toast("保存成功！");
                // 更新用户信息
                this.user.realNameAuthentication = 1;
                this.user.userName = userName
                uni.setStorageSync("user", this.user);
                setTimeout(() => {
                  navBack();
                }, 1000);
                return;
              }
              Toast(res.message);
            })
            .finally(() => {
              isLoading(false)
            })
        }

      },
      handleCamera() {
        // 如果
        this.visibleCamera = true;
      },
      hideCamera() {
        this.visibleCamera = false;
      },
      // 拍照
      takePhoto() {
        uni.showLoading({
          title: "拍摄中",
        });
        this.cameraContext.takePhoto({
          quality: "normal",
          success: (res) => {
            this.afterRead(res);
            this.visibleCamera = false;
            uni.showToast({
              title: "拍照成功",
              icon: "none",
              duration: 1200,
            });
          },
          fail: (err) => {
            uni.showToast({
              title: "拍照失败，请检查系统是否授权",
              icon: "none",
              duration: 1200,
            });
          },
        });
      },
      // 从相册选取
      chooseImage() {
        uni.chooseImage({
          count: 1,
          sizeType: ["original", "compressed"],
          sourceType: ["album"],
          success: (res) => {},
          fail: (err) => {},
        });
      },
      onParsedSuccess(value) {
        const {
          // domicileAddress,
          userName,
          idcard,
          nation
        } = value
        let nationOption = selectNation(this.dictMapping, nation)
        if (nationOption) {
          this.form.nation = nationOption.value
          this.form.nation_text = nationOption.text
        }
        // this.$set(this.form, 'domicileAddress', domicileAddress)
        this.$set(this.form, 'userName', userName)
        this.$set(this.form, 'idcard', idcard)
        this.handleIdCardChange()
        this.visibleCamera = false
      },
      onCityConfirm(event) {
        let key = this.cityPickerWithKey
        this.form[`${key}_text`] = event.address;
        this.form[`${key}`] = event.code;
        this.cityPickerVisible = false;
      },
      handleCityPicker(key) {
        this.cityPickerWithKey = key
        this.cityPickerVisible = true
      },
      getDetail() {
        AuthenticationDetail().then((res) => {
          if (res.code == 200) {
            // 拿到实名认证信息 给赋值
            this.form = Object.assign({}, this.form, pick(res.result, ['idcard', 'userName', 'mobile']));
            this.oldRealNameAuthentication = res.result;
          }
        });
      },
      handleToUploadIdcard() {
        navTo({
          url: '/selfInfo/idPhoto/idPhoto',
          params: {
            idCardImage: this.form.idCardImage,
            idCardImageBack: this.form.idCardImageBack,
            idType: this.form.idType
          }
        })
      },
      onPickerConfirm(data, formName = 'form') {
        let {
          value,
          text
        } = data.value[0];
        this[formName][this.pickerWithFormKey] = value;
        this.$set(this[formName], `${this.pickerWithFormKey}_text`, text);
        // 如果证件类型不是 10 的时候
        if (this.pickerWithFormKey === 'idType' && value != 10) {
          this.form.idCardImage = ''
          this.form.idCardImageBack = ''
        }
        this.pickerShow = false;
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }

  .u-form-item__body__right__content__slot {
    flex-direction: row !important;
  }
</style>
<style lang="scss" scoped>
  @import "../../styles/uni-form.scss";

  /deep/.u-input__content__field-wrapper__field {
    padding-right: 0;
  }

  .root {
    height: 100%;
  }

  .realNameAuthentication {
    flex: 1;
    background-color: #f3f3f3;

    .realNameAuthentication-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 10rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
      }
    }

    .tips {
      font-weight: 500;
      font-size: 28rpx;
      color: #F51616;
      line-height: 42rpx;
      padding: 49rpx 27rpx 0 27rpx;
    }

    .title-name {
      font-size: 30rpx;
      font-weight: bold;
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }

    .look-text {
      color: #2488F5 !important;
    }

    .scan-wrapper {
      padding: 10rpx;

      .scan-img {
        width: 30rpx;
        height: 27.73rpx;
      }
    }
  }
</style>